package org.dtrd.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.ibatis.reflection.MetaObject;

import java.lang.reflect.Field;

/**
 * @author xiao
 * @date 2022/5/23 2:32 PM
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        try {
            Class<?> clazz = originalObject.getClass();
            for (Field declaredField : clazz.getDeclaredFields()) {
                declaredField.setAccessible(true);
                if (declaredField.isAnnotationPresent(GenerateUUID.class) && declaredField.get(originalObject) != null) {
                    System.out.println("CustomMetaObjectHandler.insertFill declaredField=" + declaredField.getName() + "; declaredField.getClass()=" + declaredField.getClass());
                    setFieldValByName(declaredField.getName(), IdWorker.get32UUID(), metaObject);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
}
